﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace TathamOddie.OpenSearchValidator.Logic.Tasks.VisualSearch
{
	public class RetrieveVisualSearchSuggestionsTask : IValidationTask
	{
		const string VisualSearchSuggestionsMediaType = "application/x-suggestions+xml";

		string visualSearchInterfaceTemplate;

		public RetrieveVisualSearchSuggestionsTask(string visualSearchInterfaceTemplate)
		{
			this.visualSearchInterfaceTemplate = visualSearchInterfaceTemplate;
		}

		public ValidationTaskResult Validate(ValidationServices services, ValidationState state)
		{
			var result = new ValidationTaskResult();

			var queryPath = visualSearchInterfaceTemplate.Replace("{searchTerms}", state.SearchTerms);

			Uri queryUri;
			try
			{
				queryUri = new Uri(queryPath);
			}
			catch (FormatException)
			{
				result.AddMessage(MessageType.Failure, "Failed to parse [{0}] as a URI.", queryPath);
				return result;
			}

			var suggestion = DownloadHelper.Download
			(
				services.WebLoader,
				result,
				"visual search suggestions",
				true,
				queryUri,
				VisualSearchSuggestionsMediaType
			);

			if (suggestion != null)
			{
				result.ChildTasks.Add(new ValidateVisualSearchSuggestionsTask(queryUri, suggestion.Content));
			}

			return result;
		}
	}
}